package org.lanyu.springainovel.novel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.chat.vo.ImagePromptVO;
import org.lanyu.springainovel.common.vo.RestVO;
import org.lanyu.springainovel.novel.entity.Book;
import org.lanyu.springainovel.novel.service.BookService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 书籍管理控制器
 */
@Slf4j
@Tag(name = "书籍管理", description = "书籍管理相关接口")
@RestController
@RequestMapping("/novel/book")
@RequiredArgsConstructor
public class BookController {

    private final BookService bookService;
    
    @Operation(summary = "获取书籍列表", description = "分页获取用户的所有书籍")
    @GetMapping("/list")
    public RestVO<IPage<Book>> getBookList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long userId) {
        try {
            Page<Book> page = new Page<>(current, size);
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            
            if (title != null && !title.trim().isEmpty()) {
                queryWrapper.like("title", title);
            }
            
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            if (userId != null) {
                queryWrapper.eq("user_id", userId);
            }
            
            queryWrapper.orderByDesc("update_time");
            
            IPage<Book> result = bookService.page(page, queryWrapper);
            return RestVO.success(result);
        } catch (Exception e) {
            log.error("获取书籍列表失败", e);
            return RestVO.fail("获取书籍列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取书籍详情", description = "根据ID获取书籍详细信息")
    @GetMapping("/{id}")
    public RestVO<Book> getBookById(@PathVariable Long id) {
        try {
            Book book = bookService.getBookById(id);
            if (book == null) {
                return RestVO.fail("书籍不存在");
            }
            return RestVO.success(book);
        } catch (Exception e) {
            log.error("获取书籍详情失败", e);
            return RestVO.fail("获取书籍详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "创建书籍", description = "创建新的书籍")
    @PostMapping
    public RestVO<Book> createBook(@RequestBody Book book) {
        try {
            String imgUrl = book.getCoverImage();
            // 保存书籍基本信息
            book.setCoverImage(null);
            Book createdBook = bookService.createBook(book);
            
            // 如果有封面图片URL，下载并保存到本地
            if (imgUrl != null && !imgUrl.trim().isEmpty()) {
                // 只有当图片URL是以http开头的外部图片时才下载保存
                if (imgUrl.startsWith("http")) {
                    try {
                        String localImagePath = bookService.saveImageToLocal(imgUrl, createdBook.getId());
                        // 更新书籍的封面图片路径
                        createdBook.setCoverImage(localImagePath);
                        bookService.updateBook(createdBook);
                    } catch (Exception e) {
                        log.error("保存封面图片失败，但书籍创建成功", e);
                        // 不影响书籍创建，只记录错误
                    }
                }
                // 如果是以/开头的相对路径，说明已经是本地保存的图片，无需处理
            }
            
            return RestVO.success(createdBook);
        } catch (Exception e) {
            log.error("创建书籍失败", e);
            return RestVO.fail("创建书籍失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新书籍", description = "更新书籍信息")
    @PutMapping("/{id}")
    public RestVO<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        try {
            book.setId(id);
            
            // 如果有新的封面图片URL，下载并保存到本地
            if (book.getCoverImage() != null && !book.getCoverImage().trim().isEmpty()) {
                // 只有当图片URL是以http开头的外部图片时才下载保存
                if (book.getCoverImage().startsWith("http")) {
                    try {
                        String localImagePath = bookService.saveImageToLocal(book.getCoverImage(), id);
                        // 更新书籍的封面图片路径
                        book.setCoverImage(localImagePath);
                    } catch (Exception e) {
                        log.error("保存封面图片失败", e);
                        // 抛出异常，让用户知道保存失败
                        return RestVO.fail("保存封面图片失败: " + e.getMessage());
                    }
                }
                // 如果是以/开头的相对路径，说明已经是本地保存的图片，无需处理
            }
            
            Book updatedBook = bookService.updateBook(book);
            return RestVO.success(updatedBook);
        } catch (Exception e) {
            log.error("更新书籍失败", e);
            return RestVO.fail("更新书籍失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除书籍", description = "根据ID删除书籍")
    @DeleteMapping("/{id}")
    public RestVO<Boolean> deleteBook(@PathVariable Long id) {
        try {
            // 先删除数据库中的记录
            boolean success = bookService.removeById(id);
            
            if (success) {
                // 删除服务器上的书籍目录
                boolean dirDeleted = bookService.deleteBookDirectory(id);
                
                if (!dirDeleted) {
                    log.warn("书籍删除成功，但删除书籍目录失败，书籍ID: {}", id);
                    // 目录删除失败不影响整体操作结果，只记录警告
                }
                
                return RestVO.success(true);
            } else {
                return RestVO.fail("删除失败，书籍可能不存在");
            }
        } catch (Exception e) {
            log.error("删除书籍失败", e);
            return RestVO.fail("删除书籍失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新书籍状态", description = "更新书籍的状态")
    @PutMapping("/{id}/status")
    public RestVO<Book> updateBookStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            Book book = bookService.getById(id);
            if (book == null) {
                return RestVO.fail("书籍不存在");
            }
            
            book.setStatus(status);
            Book updatedBook = bookService.updateBook(book);
            return RestVO.success(updatedBook);
        } catch (Exception e) {
            log.error("更新书籍状态失败", e);
            return RestVO.fail("更新书籍状态失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户书籍", description = "获取指定用户的所有书籍")
    @GetMapping("/user/{userId}")
    public RestVO<List<Book>> getBooksByUserId(@PathVariable Long userId) {
        try {
            List<Book> books = bookService.getBooksByUserId(userId);
            return RestVO.success(books);
        } catch (Exception e) {
            log.error("获取用户书籍失败", e);
            return RestVO.fail("获取用户书籍失败: " + e.getMessage());
        }
    }

    @Operation(summary = "创建书籍封面", description = "根据提示词生成书籍封面")
    @PostMapping("/cover")
    public RestVO<String> createBookCover(@RequestBody ImagePromptVO imagePromptVO) {
        try {
            String imageUrl = bookService.createBookCover(imagePromptVO);
            return RestVO.success(imageUrl);
        } catch (Exception e) {
            log.error("创建书籍封面失败", e);
            return RestVO.fail("创建书籍封面失败: " + e.getMessage());
        }
    }
    

}